<template>
  <div class="flex">
    <div class="left mr-10">
      <!-- 左侧搜索框 -->
      <el-input
        v-model="keyword"
        class="mb-10"
        placeholder="请输入编号或名称"
        @keydown.enter="keywordSearch"
      >
        <template #prefix>
          <el-icon class="el-input__icon"><search /></el-icon>
        </template>
      </el-input>
      <!-- 左侧表格 -->
      <div class="table">
        <jg-grid ref="leftGrid" v-bind="leftGridOptions" v-on="leftGridEvent" />
      </div>
    </div>
    <div class="right">
      <div class="mb-10">
        <el-button type="primary" icon="plus" @click="btnEventAdd">新增</el-button>
        <el-button type="primary" icon="edit" @click="btnEventEdit">修改</el-button>
        <el-button type="primary" icon="delete" @click="btnEventDel">删除</el-button>
        <el-button type="primary" icon="check" @click="btnEventSave">保存</el-button>
        <el-button type="primary" icon="close" @click="btnEventCancel">取消</el-button>
      </div>
      <!-- 右上表单 -->
      <JgForm
        ref="formRef"
        :data="form.model"
        label-width="auto"
        :items="form.items"
        :form-config="formConfig"
      />
      <!-- 右下表格 -->
      <jg-grid ref="rightGrid" v-bind="rightGridOptions" v-on="rightGridEvent" />
    </div>
  </div>
</template>

<script setup lang="tsx">
import { reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getLeftTableListApi,
  getDetailApi,
  delTableListApi,
  saveTableDataApi
} from '@/api/template'

// const formStatus = ref(true) // 表单禁用状态
const keyword = ref('') // 左侧搜索框

/* ------------------------------ 左侧表格配置 ------------------------------ */
const leftGrid = ref()
const leftGridOptions = reactive({
  height: 'auto', // 表格会自动根据父容器的高度去铺满
  columns: [
    {
      field: 'pmsobjNo',
      title: '编号',
      flex: 1
    },
    {
      field: 'pmsobjName',
      title: '名称',
      flex: 1
    }
  ], // 表格列配置
  rowConfig: {
    isCurrent: true
  },
  pagerConfig: {
    layout: 'total'
  }, // 分页配置 配置则显示分页 否则不显示
  proxyConfig: {
    seq: true, // 启用动态序号代理，每一页的序号会根据当前页数变化
    sort: true, // 启用排序代理，当点击排序时会自动触发 query 行为
    filter: true, // 启用筛选代理，当点击筛选时会自动触发 query 行为
    form: true, // 启用表单代理，当点击表单提交按钮时会自动触发 reload 行为
    autoLoad: true, // 是否自动加载数据
    props: {
      // 对应响应结果 Promise<{ result: [], page: { total: 100 } }>
      result: 'result', // 配置响应结果列表字段
      total: 'total' // 配置响应结果总页数字段
    }, // 只接收Promise，具体实现自由发挥
    ajax: {
      // 当点击工具栏查询按钮或者手动提交指令 query或reload 时会被触发
      query: ({ page, sorts, filters, form, data }) => {
        console.log(11111, page, sorts, filters, form, data)
        const queryParams: any = Object.assign({}, form, { name: keyword.value }, page)
        return getLeftTableListApi(queryParams)
          .then((response) => {
            return {
              result: response.data,
              total: response.data.length
            }
          })
          .catch((err) => {
            ElMessage.warning(err)
          })
      }
    }
  }
})
let currentLeftRowId = ref('')
const leftGridEvent = {
  currentChange(e: any) {
    currentLeftRowId.value = e.row.pmsobjId
    rightGrid.value.commitProxy('query')
  }
}
function keywordSearch() {
  leftGrid.value.commitProxy('query')
}

/* ------------------------------ 右上搜索表单配置 ------------------------------ */
const formRef = ref()
const form = reactive({
  model: {},
  items: [
    {
      prop: 'pmsobjNo',
      label: '编号',
      required: true,
      attrs: {
        onInput(val) {
          console.log('no...', val)
        }
      }
    },
    {
      prop: 'pmsobjName',
      label: '名称',
      required: true,
      attrs: {
        onInput(val) {
          console.log('name...', val)
        }
      }
    },
    {
      prop: 'statusRmk',
      label: '状态',
      component: 'Jg-radio',
      attrs: {
        options: [
          { label: '有效', value: '1' },
          { label: '无效', value: '0' }
        ]
      }
    }
  ]
})
const formConfig = reactive({
  disabled: true
})

/* ------------------------------ 右下表格配置 ------------------------------ */
const rightGrid = ref()
const rightGridOptions = reactive({
  keepSource: true,
  height: '600', // 表格高度
  rowConfig: {
    isHover: true
  },
  columnConfig: {
    minWidth: 80,
    resizable: true
  },
  columns: [
    { type: 'checkbox', title: '', width: 60, fixed: 'left' },
    {
      field: 'pmsitemNo',
      title: '明细编号',
      editRender: { name: 'Input' }
    },
    {
      field: 'pmsitemName',
      title: '明细名称',
      editRender: { name: 'Input' }
    },
    {
      field: 'statusRmk',
      title: '是否使用',
      formatter: ({ cellValue }) => {
        const options = [
          { label: '使用中', value: '1' },
          { label: '未使用', value: '2' }
        ]
        const item = options.find((item) => item.value === cellValue)
        return item ? item.label : cellValue
      },
      editRender: {
        name: 'Select',
        attrs: {
          options: [
            { label: '使用中', value: '1' },
            { label: '未使用', value: '2' }
          ]
        }
      }
    }
  ], // 表格列配置
  toolbarConfig: {
    buttons: [
      { code: 'insert_actived', name: '新增', status: 'primary' },
      { code: 'delete', name: '删除', status: 'info' }
    ],
    refresh: true, // 显示刷新按钮
    zoom: true, // 显示全屏按钮
    custom: true // 显示自定义列按钮
  },
  pagerConfig: {
    total: 0
  },
  proxyConfig: {
    seq: true, // 启用动态序号代理，每一页的序号会根据当前页数变化
    sort: true, // 启用排序代理，当点击排序时会自动触发 query 行为
    filter: true, // 启用筛选代理，当点击筛选时会自动触发 query 行为
    form: true, // 启用表单代理，当点击表单提交按钮时会自动触发 reload 行为
    autoLoad: false, // 是否自动加载数据
    props: {
      // 对应响应结果 Promise<{ result: [], page: { total: 100 } }>
      result: 'result', // 配置响应结果列表字段
      total: 'total' // 配置响应结果总页数字段
    },
    // 只接收Promise，具体实现自由发挥
    ajax: {
      // 当点击工具栏查询按钮或者手动提交指令 query或reload 时会被触发
      query: ({ page, sorts, filters, form, data }) => {
        console.log(11111, page, sorts, filters, form, data)
        const queryParams: any = Object.assign({}, form, { id: currentLeftRowId.value }, page)
        return getDetailApi(queryParams)
          .then((response) => {
            copyFormData(response.data) // 给表单赋值
            return {
              result: response.data.itemPage.records,
              total: response.data.itemPage.total
            }
          })
          .catch((err) => {
            ElMessage.warning(err)
          })
      },
      // 当点击工具栏删除按钮或者手动提交指令 delete 时会被触发
      delete: ({}) => {},
      // 当点击工具栏保存按钮或者手动提交指令 save 时会被触发
      save: ({}) => {}
    }
  },
  checkboxConfig: {
    reserve: true,
    highlight: true,
    range: true
  },
  editRules: {
    name: [
      { required: true, message: '名称必填' },
      { min: 3, max: 50, message: '名称长度在 3 到 50 个字符' }
    ],
    email: [{ required: true, message: '邮件必须填写' }],
    role: [{ required: true, message: '角色必须填写' }]
  },
  editConfig: {
    trigger: 'click',
    mode: 'row',
    showStatus: true,
    beforeEditMethod() {
      return !formConfig.disabled
    }
  }
})
const rightGridEvent = {
  toolbarButtonClick({ code, $event }: any) {
    console.log('toolbar-button-click', code, $event)
    switch (code) {
      case 'insert_actived':
        break
      case 'delete':
        break
      default:
        break
    }
  }
}

function btnEventAdd() {
  formConfig.disabled = false
  form.model = {}
  formRef.value.resetFields()
  rightGrid.value.reloadData()
  rightGridOptions.pagerConfig.total = 0
}
function btnEventEdit() {
  formConfig.disabled = false
}
function btnEventDel() {
  ElMessageBox.confirm('您确定要删除所选权限对象吗？', 'Warning', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      delTableListApi(currentLeftRowId.value).then(() => {
        ElMessage.success('删除成功')
      })
    })
    .catch(() => {
      ElMessage.info('取消删除')
    })
}
function btnEventSave() {
  formRef.value.validate((valid) => {
    if (valid) {
      const tableData = rightGrid.value.getRecordset()
      const data: any = {
        ...form.model,
        deleteItems: tableData.removeRecords,
        itemInputVos: []
      }
      data.itemInputVos = [...tableData.insertRecords, ...tableData.updateRecords]
      saveTableDataApi(data)
        .then((response) => {
          console.log('save-response', response)
          formConfig.disabled = true
          leftGrid.value.commitProxy('query')
          ElMessage.success('保存成功')
        })
        .catch(() => {
          ElMessage.info('取消删除')
        })
    }
  })
}
function btnEventCancel() {
  formConfig.disabled = true
}
function copyFormData(data: any) {
  Object.assign(form.model, data)
}
</script>

<style lang="less" scoped>
.flex {
  display: flex;
  justify-content: space-between;
  background-color: #fff;
  padding: 10px;
  border-radius: 8px;
  box-sizing: border-box;

  .left {
    flex: 1;
    width: 100%;
    overflow: hidden;
    border: 1px solid #eee;
    padding: 10px;
    border-radius: 5px;
    box-sizing: border-box;

    .table {
      width: 100%;
      height: calc(100vh - 190px);
    }
  }

  .right {
    flex: 3;
    height: calc(100vh - 126px);
    padding: 10px;
    border: 1px solid #eee;
    border-radius: 5px;
    overflow: auto;
    box-sizing: border-box;
  }
}
.container {
  width: 100%;
}
.mr-10 {
  margin-right: 10px;
}
.mb-10 {
  margin-bottom: 10px;
}
</style>
